#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#define MAXNUM 10000000
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int index = 0;
int array[MAXNUM];

void *gen_even(void *arg)
{
    for (int i = 0; i < MAXNUM; i += 2)
    {
        for (int j = 0; j < 200; j++)
        {
            int k = __sync_fetch_and_add(&index, 1);
            array[k] = i;
            i += 2;
        }
    }
    // return NULL;
}

void *gen_odd(void *arg)
{
    for (int i = 0; i < MAXNUM; i += 2)
    {
        for (int j = 0; j < 200; j++)
        {
            int k = __sync_fetch_and_add(&index, 1);
            array[k] = i + 1;
            i += 2;
        }
    }
    // return NULL;
}


int main()
{
    struct timeval tv1, tv2;
    pthread_t p_odd, p_even;
    gettimeofday(&tv1, NULL);
    pthread_create(&p_even, NULL, gen_even, NULL);
    pthread_create(&p_odd, NULL, gen_odd, NULL);
    pthread_join(p_even, NULL);
    pthread_join(p_odd, NULL);
    int minus = 0;

    for (int i = 1; i < MAXNUM; i++)
    {
        int temp = abs(array[i] - array[i - 1]);
        minus = MAX(minus, temp);
    }
    gettimeofday(&tv2, NULL);
    printf("max minus is: %d\n", minus);
    printf("time cost is: %dus\n", tv2.tv_usec - tv1.tv_usec);

    return 0;
}